<template>
  <div>
    <div class="select-box">
      <el-form :inline="true" :model="data.selectData" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="data.selectData.title" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="详情">
          <el-input v-model="data.selectData.introduce" placeholder="请输入关键字"> </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="dataList.comList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="introduce" label="详情" />
    </el-table>
    <el-pagination @current-change="currentChange" @size-change="sizeChange" layout="prev, pager, next" :total="data.selectData.count * 2" />
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, watch } from 'vue'
import { getGoodsList } from '../request/api'
import { InitData, ListInt } from '../type/goods'
const data = reactive(new InitData())

getGoodsList().then((res) => {
  data.list = res.data
  data.selectData.count = res.data.length
})

const onSubmit = () => {
  let arr: ListInt[] = [] // 定义数组，接收查询之后展示的数据
  if (data.selectData.title || data.selectData.introduce) {
    // 判断输入框中是否有值
    if (data.selectData.title) {
      arr = data.list.filter((value) => {
        // 将过滤出来的数组赋值给arr
        return value.title.indexOf(data.selectData.title) !== -1
      })
    }
    if (data.selectData.introduce) {
      arr = data.list.filter((value) => {
        // 将过滤出来的数组赋值给arr
        return value.introduce.indexOf(data.selectData.introduce) !== -1
      })
    }
  } else {
    arr = data.list
  }
  data.selectData.count = arr.length
  data.list = arr
}
// 监听输入框的两个属性
watch([() => data.selectData.title, () => data.selectData.introduce], () => {
  if (data.selectData.title == '' && data.selectData.introduce == '') {
    getGoodsList().then((res) => {
      data.list = res.data
      data.selectData.count = res.data.length
    })
  }
})

const currentChange = (page: number) => {
  data.selectData.page = page
}
const sizeChange = (pagesize: number) => {
  data.selectData.page = pagesize
}
const dataList = reactive({
  comList: computed(() => {
    return data.list.slice((data.selectData.page - 1) * data.selectData.pagesize, data.selectData.page * data.selectData.pagesize)
  }),
})
</script>

<style scoped>
.el-pagination {
  display: flex;
  justify-content: center;
}
</style>
